import os
import uuid

import requests
from io import BytesIO
from PIL import Image
import random
import time

# ========== 配置 ==========
ACCESS_KEY = 'GwfAfoK3njIMZxUPVxzAF2Pp489sc4oFbAa6fIcxZIg'   # <<<< 换成你自己的

SAVE_DIR = 'unsplash_images'
TOTAL_IMAGES = 10
MAX_SIZE = 640

# 类别和关键词设置
CATEGORIES = {
    "young": {
        "keywords": [
            "Japan beautiful woman", "Japan beautiful girl"
        ],
        "count": int(TOTAL_IMAGES * 1)
    },
   # "cartoon": {
  #      "keywords": ["anime portrait", "cartoon character", "cartoon avatar"],
   #     "count": int(TOTAL_IMAGES * 0.2)
   # },
   # "abstract": {
  #      "keywords": ["abstract art", "abstract painting", "colorful abstract"],
   #     "count": TOTAL_IMAGES - int(TOTAL_IMAGES * 0.7) - int(TOTAL_IMAGES * 0.2)
  #  },
}

HEADERS = {
    "Accept-Version": "v1",
    "Authorization": f"Client-ID {ACCESS_KEY}"
}

# ========== 功能函数 ==========

def search_unsplash(keyword, per_page=30, page=1):
    url = f"https://api.unsplash.com/search/photos"
    params = {
        "query": keyword,
        "per_page": per_page,
        "page": page,
       # "orientation": "squarish"
    }
    try:
        response = requests.get(url, headers=HEADERS, params=params, timeout=10)
        if response.status_code == 200:
            data = response.json()
            return [item['urls']['regular'] for item in data.get('results', [])]
        else:
            print(f"[!] Search failed: {response.status_code} {response.text}")
            return []
    except Exception as e:
        print(f"[!] Search error: {e}")
        return []

def download_and_resize(url, save_path, max_size=640):
    try:
        response = requests.get(url, timeout=10)
        if response.status_code == 200:
            img = Image.open(BytesIO(response.content)).convert("RGB")

            # 只按比例缩放，最长边等于max_size
            w, h = img.size
            if w > h:
                new_w = max_size
                new_h = int(h * (max_size / w))
            else:
                new_h = max_size
                new_w = int(w * (max_size / h))

            img = img.resize((new_w, new_h), Image.LANCZOS)

            os.makedirs(os.path.dirname(save_path), exist_ok=True)
            img.save(save_path, quality=95)
            return True
    except Exception as e:
        print(f"[!] Download error: {e}")
    return False

# ========== 主逻辑 ==========

def main():
    total_downloaded = 0
    for category, info in CATEGORIES.items():
        count_needed = info['count']
        keywords = info['keywords']
        save_category_dir = os.path.join(SAVE_DIR, category)
        os.makedirs(save_category_dir, exist_ok=True)

        print(f"[+] Start downloading {count_needed} images for category: {category}")
        while count_needed > 0:
            keyword = random.choice(keywords)
            print(f"    [-] Searching: {keyword}")
            image_urls = search_unsplash(keyword, per_page=30, page=random.randint(1, 10))

            if not image_urls:
                print(f"    [!] No images found for keyword {keyword}")
                continue

            for url in image_urls:
                if count_needed <= 0:
                    break
                filename = f"{uuid.uuid4().hex}.jpg"
                save_path = os.path.join(save_category_dir, filename)
                success = download_and_resize(url, save_path, MAX_SIZE)
                if success:
                    total_downloaded += 1
                    count_needed -= 1
                    print(f"    [+] Downloaded: {filename}")
                time.sleep(0.5)  # 稍微慢一点，避免触发限速

    print(f"[✓] Finished downloading {total_downloaded} images.")

if __name__ == "__main__":
    main()
